package com.ruoyi.uni.framework;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.uni.util.CODE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class uniInterceptor implements HandlerInterceptor {
    @Autowired
   private RedisCache redisCache;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getHeaderNames());
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("token"));
        if(request.getRequestURI().equals("/uni/login")){
            return true;
        }else{
            String token = request.getHeader("token");
            System.out.println(token);
            response.setCharacterEncoding("utf8");
            response.setContentType("application/json;charset=utf8");
            if(token==null){
                response.getWriter().write("{\"code\":"+ CODE.TOKEN_NULL+"}");
                return false;
            }else if(!redisCache.hasKey(token)){
                response.getWriter().write("{\"code\":"+ CODE.TOKEN_OVER_DUE+"}");
                return false;

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
